const express = require('express')
const buuid = require('binary-uuid')
const moment = require('moment-timezone')
const models = require('../models')

moment.tz.setDefault("Asia/Shanghai")

const QRCode = models.QRCode

function utcNow() {
    return new Date((moment().format("yyyy-MM-DDTHH:mm:00") + 'Z'))
}

function uuidv4() {
    // 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    return 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
        var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

async function create(record) {
    try {
        let res = await QRCode.create(record)
        return true
    } catch (e) {
        if (e && e.original && e.original.code === 'ER_DUP_ENTRY') {
            console.log(`ER_DUP_ENTRY, retrying...`)
        } else {
            console.log(e)
        }
        return false
    }
}

async function createMany(records) {
    let count = 0
    let conflict = 0

    for (let i = 0; i < records.length; i++) {
        let ele = records[i];
        let maxTry = 10
        let res = await create(ele)
        while (res == false && maxTry > 0) {
            maxTry--
            conflict++
            console.log(maxTry)
            let uuid = uuidv4()
            let buuid = buuid.toBinaryUUID(uuid)
            // let uuid = id
            ele.uuid = buuid
            ele.code = uuid
            res = await create(ele)
        }
        if (res == true) {
            count++
        }
    }
    return { count, conflict }
}

const router = express.Router()

router.post('/batch_generate', async (req, res) => {
    console.log(req.body)
    let batch
    if (req.body.batch) {
        batch = req.body.batch
    } else {
        batch = uuidv4().substr(0, 6)
    }
    if (req.body && req.body.number > 0 && req.body.number <= 1000) {
        let qrcodes = []
        let createdAt = utcNow()
        for (let i = 0; i < req.body.number; i++) {
            const uuid = uuidv4()
            const qr = {
                consumableType: req.body.consumableType,
                // amount: req.body.amount,
                uuid: buuid.toBinaryUUID(uuid),
                code: uuid,
                createdAt: createdAt,
                updatedAt: createdAt,
                batch: batch
            }
            if (req.body.expireDate) {
                qr.expireDate = new Date(req.body.expireDate)
            }
            qrcodes.push(qr)
        }
        let result = await createMany(qrcodes)
        res.json(result)
    } else {
        res.json({ status: -1, msg: '请求数量不在允许范围(1-1000)' })
    }
})

console.log(buuid.toBinaryUUID(uuidv4()))

module.exports = { qrcodeApi: router, create, createMany, uuidv4 } 